from rest_framework import serializers
from bookTest.models import Book
from rest_framework.exceptions import ValidationError

# class BookSerializers(serializers.Serializer):

#     name = serializers.CharField()
#     price = serializers.DecimalField(max_digits=10, decimal_places=2)
#     createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")

#     def create(self, validated_data):
#         book = Book.objects.create(**validated_data)
#         return book

#     def update(self, instance, validated_data):
#         instance.name = validated_data.get("name")
#         instance.price = validated_data.get("price")
#         # instance.createTime = validated_data.get("createTime")
#         instance.save()
#         return instance

#     def validate_name(self, name):
#         if name.startswith('SB'):
#             raise ValidationError("名称不能已SB开头")
        
#         return name
class BookSerializers(serializers.ModelSerializer):

    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", label="创建时间", read_only=True)

    # createTimes = serializers.DateTimeField(source='createTime')

    class Meta:
        model = Book
        fields  = '__all__'
       
        extra_kwargs = {
            'name':{'max_length': 8},
        }

    def validate(self, attrs):
        if attrs.get("name").startswith("SB"):
            raise ValidationError("名称不能以SB开头")

        return attrs



    